import 'package:get/get.dart';
import 'package:oktoast/oktoast.dart';
import 'package:sp_util/sp_util.dart';
import 'package:yp/config/config.dart';
import 'package:yp/pages/main/logic.dart';
import 'package:yp/router.dart';
import 'package:yp/services/api.dart';

import 'state.dart';

class MyLogic extends GetxController {
  final state = MyState();
  // final MainAppLogic mainAppLogic = Get.put(MainAppLogic());
  final MainLogic mainLogic = Get.put(MainLogic());
  @override
  void onInit() {
    super.onInit();

    reload();
  }

  void reload() {
    keFu();
    personInfo();
    getWelfareCardList();
    couponsInfo();
    integralInfo();
    diyConfigure();
    queryTask();
    getrecommendGoods();
    surpriseQuery();
  }
  // 评价有礼
  void surpriseQuery() {
    var params = {
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'channel_num_id': 99,
      'award_types': [604],
      'access_token': SpUtil.getString('token'),
      'sub_unit_num_id': SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      'ec_shop_num_id': SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    };
    Api.surpriseQuery(params).listen((event) {
      print('评价有礼 返回数据   event = $event');
      if (event['code'] == 0) {
        List list = event['member_surprise_task_infos'];
        if (list.length > 0) {
          state.pingJiaList = list;
        }
      }
      update();
    }, onDone: () {

    });
  }
  // 签到刷新
  void signInRefresh() {
    integralInfo();
    queryTask();
  }

// 获取用户信息
  personInfo() {
    var params = {
      'access_token': SpUtil.getString('token'),
      'mobile': SpUtil.getString('number'), 
    };
    Api.searchMember(params).listen((event) {
      if (event['code'] == 0) {
        state.userInformationData = event;
      } else {
        state.userInformationData = null;
      }
      if (state.controller1.isRefresh) {
        state.controller1.refreshCompleted();
      }
      update();
    });
  }

  /// 获取福利卡列表
  void getWelfareCardList() {
    Map<String, dynamic> params = {
      "use_platform": 2,
      "user_num_id:": SpUtil.getInt('empeNumId'),
      "card_status": 3,
      "access_token": SpUtil.getString('token'),
    };

    Api.getWelfareCardList(params).listen((event) {
      print("获取福利卡列表==========$event");
      if (event["code"] == 0 && event["available_cards"] != null) {
        state.walletNum = event["total_available_amount"];
        update();
      }
    });
  }

// 获取优惠券数量
  couponsInfo() {
    var paramsCoupons = {
      'use_platform': 2,
      'access_token': SpUtil.getString('token'),
      'status': '1',
      'page': 1,
      'rows': 10,
      'usr_num_id': SpUtil.getInt('empeNumId'),
    };
    Api.availableCouponsList(paramsCoupons).listen((event) {
      if (event['code'] == 0) {
        state.availableCouponsNum = event['total'];
      }
      update();
    });
  }

// 获取积分
  integralInfo() {
    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
    };
    Api.userIntegral(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        state.userIntegralNum = event['point'];
      }
      update();
    });
  }

  // 钱包信息
  wallertInfo() {
    var paramsWallet = {
      'access_token': SpUtil.getString('token'),
      'card_status': 3,
    };
    Api.walletInformation(paramsWallet).listen((event) {
      if (event['code'] == 0) {
        state.walletNum = event['total_available_amount'];
      }
      print('==========  state.walletNum = ${state.walletNum}');
      update();
    });
  }

// 获取会员中心个性化配置
  diyConfigure() {
    var paramsDiy = {
      // 'ec_shop_num_id': SpUtil.getInt('storeShopNum'),
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
    };
    Api.personalizedConfiguration(paramsDiy).listen((event) {
      if (event['code'] == 0) {
        state.diyConfigData = event;
        state.taskData = [];
        if (event['personal_config_mem_center']['member_task_sign'] == 1) {
          queryTask();
        }
      }
      update();
    });
  }

  // 获取客服信息
  void keFu() {
    print('获取客服信息 ======== 获取客服信息11111111');
    Api.MaterialGoodsSelect1({"config_name": "platform_ec_shop_num_id"})
        .listen((event) {
      print('获取客服信息 ======== 获取客服信息 ********  event = $event');
      var configValue = event["config_value"];
      Api.getAccessID(configValue.toString()).listen((event) {
        print('获取客服信息 ======== 获取客服信息  event = $event');
        // state.accessID = event["access_id"];
        state.keFuString = event['access_id'];
        update();
      });
    });
  }

  // 做任务得奖励
  void queryTask() {
    var params2 = {
      "channel_num_id": 98,
      "use_platform": 3,
      "sub_unit_num_id": 102002,
      // "ec_shop_num_id": SpUtil.getInt('storeShopNum'),
      "ec_shop_num_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      'access_token': SpUtil.getString('token'),
      "data_sign": 0,
    };
    Api.surpriseDayQuery(params2).listen((event) {
      if (event['code'] == 0) {
        if (event['do_tasks'] == 1) {
          state.taskData = _getTaskData(event);
        }
      }
      update();
    });
  }

  List<MyTaskModel> _getTaskData(event) {
    List<MyTaskModel> _list = [];
    if (event['complete_activity_sign'] == 1 &&
        event['complete_award_sign'] == 0) {
      var mod = MyTaskModel(
          id: 1, icon: 'my_task_info', name: '完善会员信息有礼', actionText: '去完善');
      _list.add(mod);
    }
    if (event['sign_in_rule_type'] == 1) {
      var mod = MyTaskModel(
          id: 2,
          icon: 'my_task_sign',
          name: '签到有礼',
          actionText: event['sign_in_award_type'] == 1 ? '已签到' : '去签到');

      _list.add(mod);
    }
    if (event['invite_activity_sign'] == 1) {
      var mod = MyTaskModel(
          id: 3, icon: 'my_task_invite', name: '邀请好友,得奖励', actionText: '去邀请');
if(Config.loginScreenStyle=='0') {
    _list.add(mod);
}
    }
    return _list;
  }

  @override
  void onReady() {
    super.onReady();
    _queryCount();
  }

  void _queryCount() {
    // gyq add
    // 查询订单数量
    var queryCondition = {
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };
    Api.queryOrderCount(queryCondition).listen((event) {
      if (event['code'] == 0) {
        //提取不同订单状态下的数量
        var orders = event['orders'];
        print(orders);
        for (Map<String, dynamic> item in orders) {
          switch (item['order_status']) {
            case 1: //未付款订单总数
              state.unPayCount = item['total_count'].toString();
              //state.unPayCount = '10';
              break;
            case 2: //已经付款订单总数
              state.arrivedCount = item['total_count'].toString();
              //state.arrivedCount = '20';
              break;
            case 3: //已发货订单总数
              state.notSendCount = item['total_count'].toString();
              break;
            case 4: //待评价订单总数
              state.unCommentCount = item['total_count'].toString();
              break;
            case 17: //退款订单总数
              state.serviceCount = item['total_count'].toString();

              break;
          }
        }
      }
      update();
    });

    // 获取积分
    var paramsIntegral = {
      'access_token': SpUtil.getString('token'),
    };
    Api.userIntegral(paramsIntegral).listen((event) {
      if (event['code'] == 0) {
        state.userIntegralNum = event['point'];
      }
      update();
    });
  }

  // 下拉 刷新
  void refreshData() {
    reload();
    _queryCount();
    getrecommendGoods();
  }

  void applyToMarketing() {
    var params = {
      'leader_usr_num_id': SpUtil.getInt('empeNumId'),
      "access_token": SpUtil.getString('token'),
    };

    Api.applyquery(params).listen((event) {
      if (event['code'] == 0) {
        if (event['distribution_salesperson_apply'] == null) {
          Get.toNamed(RouteConfig.applyExpert,
              arguments: state.userInformationData);
        } else {
          // Get.toNamed(RouteConfig.applyExpert, arguments: state.userInformationData);
          Get.toNamed(RouteConfig.expertUnderReview);
        }
      }
    });
  }

  getrecommendGoods() {
    var locationResult = SpUtil.getObject(Config.USER_CURRENT_LOCATION);
    if (locationResult == null && locationResult['AMapResult'] == null) return;
    var defaultAddress = locationResult['AMapResult'];
    var params = {
      'data_sign': 0,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
      "use_platform": 2,

      "channel_num_id": 98, //死值,推荐商品
      // "shop_id": SpUtil.getInt('storeShopNum'),
      "shop_id": SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'],
      // "prv_num_id": "320000",
      "city_num_id": defaultAddress['city_code'],
      // "city_area_num_id": "320583",
      "page_no": 1,
      "page_size": 10,
    };
    Api.memRecommendGoods(params).listen((event) {
      if (event["code"] == 0) {
        if (event['lists'] != null && event['lists'].length > 0) {
          List list = event['lists'];
          for (int i = 0; i < list.length; i ++) {
            var goods = list[i];
            if (goods['style_store'] <= 0) {
              list.remove(goods);
              list.add(goods);
            }
          }
          state.goodList = list;
        }
        update();
      }
    });
  }

  void requestAddGoods(Map goods) {
    String itemNumId = goods['default_item_num_id'].toString();
    // String ecShopNumId = SpUtil.getInt('storeShopNum').toString();
    String ecShopNumId = goods['shop_num_id'] != null
        ? goods['shop_num_id'].toString()
        : SpUtil.getObject(Config.GET_SHOP_INFO)['shop_id'];
    String styleNumId = goods['style_num_id'].toString();
    String ecStyleNumId = goods['ec_style_num_id'].toString();

    var params = {
      "use_platform": 2,
      "usr_num_id": SpUtil.getInt('empeNumId'),
      "emp_num_id": 0,
      "channel_num_id": 99,
      "quantity": 1.0,
      "ec_shop_num_id": ecShopNumId,
      "item_num_id": itemNumId,
      "style_num_id": styleNumId,
      "ec_style_num_id": ecStyleNumId,
      'access_token': SpUtil.getString('token'),
    };
    Api.addShoppingCart(params).listen((event) {
      if (event['code'] == 0) {
        showToast('加入购物车成功');
        mainLogic.getCartNum();
      } else {
        showToast(event['message']);
      }
    });
  }
}
